<?php

$groups = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_groups ORDER BY title ASC");
$currencies = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_currencies ORDER BY title ASC");




if(Antz_IntelliForm::submitted('new')){
	$error = false;
	$keyname = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', post('keyname'));
	$title = post('title');
	$grps = preg_replace('/[^a-zA-Z0-9,]/', '', post('groups'));
	$numPrices = (int) post('numPrices');
	$duration = (int) post('duration');
	$isActive = (int) post('isActive');
	if($this->CheckPermission($this->GetName().' PHP')) $code = post('code');
	else $code = '';

	// begin checks
	if($DB->countRows(cms_db_prefix().'isubscribe_subscriptions', "keyname = '{$keyname}'")>0){
		$error = true;
		Antz::addFormError('keyname', $this->Lang('already_registered_sub'));
	};
	if(trim($title)==''){
		$error = true;
		Antz::addFormError('title');
	};

	$grps = explode(',', $grps);
	$noGroups = true;
	foreach($grps as $k=>$group){
		if($DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$group}'")>0){
			$noGroups = false;
		}else{
			unset($grps[$k]);
		};
	};

	if($noGroups && trim($code)==''){
		$error = true;
		if($this->CheckPermission($this->GetName().' PHP')) $extra = $this->Lang('error_groups_extra');
		else $extra = '';
		Antz::addFormError('groups', $this->Lang('error_groups').$extra);
		if($this->CheckPermission($this->GetName().' PHP')) Antz::addFormError('code', $this->Lang('enter_code_here'));
	};

	if($this->CheckPermission($this->GetName().' PHP')){
		if(trim($code)!=''){
			if(!Antz_Filter::checkPHPCode($code)){
				$error = true;
				Antz::addFormError('code', $this->Lang('error_code'));
			};
		};
	}

	$prices = array();
	for($i=0; $i<$numPrices; $i++){
		$cur = post('cur_'.$i);
		$price = (float) post('price_'.$i);
		$grp = preg_replace('/[^a-zA-Z0-9\-_]/', '', post('group_'.$i));
		if($price > 0 && $DB->countRows(cms_db_prefix().'isubscribe_currencies', "keyname = '{$cur}'")>0 && $DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$grp}'")>0){
			$prices[] = array(
				'currency' => $cur,
				'price' => $price,
				'group' => $grp
			);
		};
	};
	if(count($prices)==0){
		$error = true;
		Antz::addError($this->Lang('error_price'));
	};
	if($duration < 0){
		$error = true;
		Antz::addFormError('duration', $this->Lang('error_duration'));
	};

	if(!$error){
		// ok to create the new subscription

		$dbParams = array(
			'keyname' => $keyname,
			'groups' => implode(',', $grps),
			'title' => $title,
			'description' => '',
			'duration' => $duration,
			'is_active' => $isActive
		);

		if($this->CheckPermission($this->GetName().' PHP')) $dbParams['php_code'] = $code;

		$subId = $DB->insert(cms_db_prefix().'isubscribe_subscriptions', $dbParams);

		foreach($prices as $k=>$v){
			$dbParams = array(
				'subscription_id' => $subId,
				'currency_key' => $v['currency'],
				'price' => $v['price'],
				'group_key' => $v['group']
			);

			$DB->insert(cms_db_prefix().'isubscribe_subscription_prices', $dbParams);

		};

		Antz::addSuccess($this->Lang('success_new_sub'));
		Antz::redir($actionUrls['edit']);

	};

};







$form = Antz::newObject('Antz_Form', 'new');
$form->setAction($actionUrls['new']);
$form->setId('new_form');

$block = $form->add('full');

$fs = $block->add($this->Lang('prices_for_sub'));
$fs->setId('fs1');

// currencies dummy for javascript to clone
$curSel = Antz::newObject('Antz_Form_Components_Select', array('cur_', $this->Lang('currency'), post('cur_')));
foreach($currencies as $k=>$cur){
	$curSel->add($cur['title'], $cur['keyname']);
};
$curSel->setId('currenciesDummy');
$fs->addLongTag('div', $curSel->render())->addParameter('style', 'display: none');

// groups dummy for javascript to clone
$groupSel = Antz::newObject('Antz_Form_Components_Select', array('group_', $this->lang('group'), post('group_')));
foreach($groups as $k=>$v){
	$groupSel->add($v['title'], $v['keyname']);
};
$groupSel->setId('groupsDummy');
$fs->addLongTag('div', $groupSel->render())->addParameter('style', 'display: none');


// link to add another price
$addLink = '
<a href="javascript: ISubscribe_Admin.addPrice()" class="pageoptions">
<img src="themes/NCleanGrey/images/icons/system/newobject.gif" 
class="systemicon" alt="'.$this->Lang('add_price').'" 
title="'.$this->Lang('add_price').'" />'.$this->Lang('add_price').'
</a> 
';
$fs->addLongTag('p', $addLink);

// re-create the currencies if the form has been submitted and returned with errors
$numPrices = (int) post('numPrices');
$fs->addInput('hidden', 'numPrices', '&nbsp;', $numPrices);
for($i=0; $i<$numPrices; $i++){
	$delLink = '
    <a href="javascript: ISubscribe_Admin.delPrice('.$i.')">
    <img src="themes/NCleanGrey/images/icons/system/delete.gif" alt="'.
    $this->Lang('delete_price').'" title="'.$this->Lang('delete_price').'" /></a>';

	// currency for this price
	$curSel = Antz::newObject('Antz_Form_Components_Select', array('cur_'.$i, 'Currency '.$i, post('cur_'.$i)));
	foreach($currencies as $k=>$cur){
		$curSel->add($cur['title'], $cur['keyname']);
	};
	$curSel->showLabel(false);
	$curSel->setWrap(false);

	// groups for upgrading
	$groupSel = Antz::newObject('Antz_Form_Components_Select', array('group_'.$i, 'Group '.$i, post('group_'.$i)));
	foreach($groups as $k=>$v){
		$groupSel->add($v['title'], $v['keyname']);
	};
	$groupSel->showLabel(false);
	$groupSel->setWrap(false);

	// lets now assemble the price component
	$component = $fs->addInput('text', 'price_'.$i, 'Price', post('price_'.$i));
	$component->addAftertext($curSel->render());
	$component->addAftertext($groupSel->render());
	$component->addAftertext($delLink);
	$component->setId('price_'.$i);
};

//$fs->addLongTag('a', $this->Lang('add_price'))->addJsEvent('href', 'javascript: ISubscribe_Admin.addPrice()');


$fs = $block->add($this->Lang('sub_details'));

$fs->addInput('text', 'keyname', $this->Lang('keyname'), post('keyname'));
$fs->addInput('text', 'title', $this->Lang('title'), post('title'));
$newGroupLink = '<a href="'.str_replace(array('ISubscribe', 'active_tab=new'), array('IUsers', 'active_tab=groups'), $actionUrls['new']).'">'.$this->Lang('add_group').'</a>';

// grant groups selection
$txt = $fs->addInput('textarea', 'groups', $this->Lang('groups_to_grant'), post('groups'));
$sel = Antz::newObject('Antz_Form_Components_Select', array('group', 'Group', '', $newGroupLink));
$sel->add($this->Lang('add_remove_groups'), '');
foreach($groups as $k=>$v){
	$sel->add($v['title'], $v['keyname']);
};
$sel->showLabel(false);
$sel->setWrap(false);
$sel->addJsEvent('onchange', 'ISubscribe_Admin.toggleGroup(this, \''.$txt->getId().'\')');
$txt->addAftertext($sel->render());
$txt->addClass('groups');

if($this->CheckPermission($this->GetName().' PHP')) $fs->addInput('textarea', 'code', $this->lang('code_notes'), post('code'));

$fs->addInput('text', 'duration', 'Duration (days)', post('duration', '365'))->addAftertext($this->Lang('0_never_expires'));

$chk = $fs->addCheckboxGroup('isActive');
$chk->add('isActive', $this->Lang('is_active'), '1', post('isActive', '1'));

$fs->addInput('submit', 'submitBtn', '&nbsp;', 'Submit');


echo $form->render();
